package com.study.lxy.newbatis.sqlSession;

import com.study.lxy.newbatis.entity.User;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MyExcutor implements Excutor {

    private MyConfiguration xmlConfiguration = new MyConfiguration();

    public <T> List<T> query(String sql, Class<T> classz) throws Exception {
        Connection connection=getConnection();
        ResultSet set =null;
        PreparedStatement pre =null;
        try {
            pre = connection.prepareStatement(sql);
            set = pre.executeQuery();
            List<T> resultList = new ArrayList<>();
            List<Method> methodsList = new ArrayList<>();
            Method[] methods = classz.getMethods();
            for(Method m : methods) {
                if(m.getName().startsWith("set")){
                    methodsList.add(m);
                    System.out.println("method names " + m.getName());
                }
            }
            //遍历结果集
            while(set.next()){
                T t = classz.newInstance();
                for(Method m : methodsList) {
                    if(m.getParameterTypes().length > 0 && m.getParameterTypes()[0].getName().contains("String")){
                        try {
                            m.invoke(t, set.getString(m.getName().substring(3).toLowerCase()));
                        } catch (SQLException se){
                            System.out.println("SQL EXCEPTION : " + se.getErrorCode() + "," + se.getSQLState() + "," + se.getMessage());
                        }
                    }
                }
                resultList.add(t);
            }
            return resultList;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            try{
                if(set!=null){
                    set.close();
                }if(pre!=null){
                    pre.close();
                }if(connection!=null){
                    connection.close();
                }
            }catch(Exception e2){
                e2.printStackTrace();
            }
        }
        return null;
    }

    private Connection getConnection() {
        try {
            Connection connection =xmlConfiguration.build("newbatis_Config.xml");
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
